package biznussoft.fieldservice360.fragments;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
import biznussoft.fieldservice360.HomeActivity;
import biznussoft.fieldservice360.R;
import biznussoft.fieldservice360.adapter.ContactsAdapter;
import biznussoft.fieldservice360.listeners.GlobalListener;
import biznussoft.fieldservice360.lookup.AccountLookup;
import biznussoft.fieldservice360.model.Bean_Class;
import biznussoft.fieldservice360.model.ContactsModel;
import biznussoft.fieldservice360.utils.Session;

import com.google.gson.Gson;
import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class AccountsdetailsFragment extends BaseFragment implements
OnClickListener {

	private Dialog progressDialog;
	private ScrollView svAccount;
	private LinearLayout llayout;
	private TableLayout tbContactdisplaylayout;
	public static EditText etParentAccount;
	private EditText etAccountNumber, etAccountName, etAnnuaLRevenue,
	etEmployees, etPhone, etfax, etwebsite, etBilingStreet,
	etBilingCity, etBilingState, etBilingZip, etBilingcountry,
	etShippingStreet, etShippingcity, etshippingstate, etShippingcode,
	etShippingCountry;
	private TextView tvAccountOwner, tvAccountNumber, tvAccountName,
	tvParentAccount, tvAnnuaLRevenue, tvEmployees, tvPhone, tvfax,
	tvWebsite, tvBilingStreet, tvBilingCity, tvBilingState,
	tvBilingZip, tvBilingcountry, billingToShipping, tvRating,
	tvOwnership, tvType, tvIndustry, tvShippingStreet, tvShippingcity,
	tvshippingstate, tvShippingcode, tvShippingCountry;
	private RestClient client;
	private Button mSave, mCancel;
	private Spinner mType, mIndustry, mRating, mOwnerShip;
	private Bean_Class bean;
	private String parantAccountID;
	static ArrayList<ContactsModel> contactList;
	private ListView abc;
	boolean flag;
	private Bundle args;
	MenuItem addAccount, addContact, edit, logout;
	private GlobalListener mHomeItemListener;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.account_details_fragment, null);
	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		mHomeItemListener = (GlobalListener) (activity);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);

	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		addAccount = menu.add("Account");
		MenuItemCompat.setShowAsAction(addAccount,
				MenuItemCompat.SHOW_AS_ACTION_ALWAYS
				| MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		addAccount.setIcon(R.drawable.add);
		addContact = menu.add("Contact");
		MenuItemCompat.setShowAsAction(addContact,
				MenuItemCompat.SHOW_AS_ACTION_ALWAYS
				| MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		addContact.setIcon(R.drawable.add);
		edit = menu.add("Edit");
		MenuItemCompat.setShowAsAction(edit,
				MenuItemCompat.SHOW_AS_ACTION_ALWAYS
				| MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		edit.setIcon(R.drawable.edit);
		logout = menu.add("Logout");
		MenuItemCompat.setShowAsAction(logout,
				MenuItemCompat.SHOW_AS_ACTION_ALWAYS
				| MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		logout.setIcon(R.drawable.logout);

		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getTitle().equals("Logout")) {
			SalesforceSDKManager.getInstance().logout(getActivity());
		}
		if (item.getTitle().equals("Contact")) {
			edit.setVisible(false);
			llayout.setVisibility(View.GONE);
			parantAccountID = bean.getId();
			String strArray[] = new String[] { bean.getBillingCountry(),
					bean.getBillingCity(), bean.getBillingState(),
					bean.getBillingStreet(), bean.getBillingPostalCode(),
					bean.getPhno(), bean.getName(), parantAccountID };
			mHomeItemListener.onNewContact(strArray);
		}
		if (item.getTitle().equals("Account")) {
			edit.setVisible(false);
			etAccountNumber.setText("");
			etAccountName.setText("");
			etAnnuaLRevenue.setText("");
			etBilingCity.setText("");
			etBilingcountry.setText("");
			etBilingState.setText("");
			etBilingStreet.setText("");
			etBilingZip.setText("");
			etEmployees.setText("");
			etfax.setText("");
			etParentAccount.setText("");
			etPhone.setText("");
			etShippingcity.setText("");
			etShippingcode.setText("");
			etShippingCountry.setText("");
			etshippingstate.setText("");
			etShippingStreet.setText("");
			etwebsite.setText("");
			tbContactdisplaylayout.setVisibility(View.GONE);
			llayout.setVisibility(View.GONE);
			svAccount.setVisibility(View.VISIBLE);
			billingToShipping.setVisibility(View.VISIBLE);
		}
		if (item.getTitle().equals("Edit")) {
			flag = true;
			edit.setVisible(false);
			tbContactdisplaylayout.setVisibility(View.GONE);
			llayout.setVisibility(View.GONE);
			svAccount.setVisibility(View.VISIBLE);
			billingToShipping.setVisibility(View.VISIBLE);
			editAcount();
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);

		tbContactdisplaylayout = (TableLayout) getView().findViewById(
				R.id.ttLayout);
		svAccount = (ScrollView) getView().findViewById(R.id.accountScrooview);
		llayout = (LinearLayout) getView().findViewById(R.id.llDisplayLayout);
		tvAccountOwner = (TextView) getView().findViewById(R.id.tvAccountOwner);
		tvAccountName = (TextView) getView().findViewById(R.id.tvAccountName);
		tvAccountNumber = (TextView) getView().findViewById(
				R.id.tvAccountNumber);
		tvPhone = (TextView) getView().findViewById(R.id.tvPhone);
		tvWebsite = (TextView) getView().findViewById(R.id.tvWebSite);
		tvAnnuaLRevenue = (TextView) getView().findViewById(
				R.id.tvAnnualRevenue);
		tvEmployees = (TextView) getView().findViewById(R.id.tvEmpoyees);
		tvfax = (TextView) getView().findViewById(R.id.tvFax);
		tvBilingStreet = (TextView) getView()
				.findViewById(R.id.tvBillingStreet);
		tvBilingCity = (TextView) getView().findViewById(R.id.tvBillingCity);
		tvBilingState = (TextView) getView().findViewById(R.id.tvBillingState);
		tvBilingZip = (TextView) getView().findViewById(R.id.tvBillingCode);
		tvBilingcountry = (TextView) getView().findViewById(
				R.id.tvBillingCountry);
		tvShippingStreet = (TextView) getView().findViewById(
				R.id.tvShippingStreet);
		tvShippingcity = (TextView) getView().findViewById(R.id.tvShippingCity);
		tvshippingstate = (TextView) getView().findViewById(
				R.id.tvShippingState);
		tvShippingcode = (TextView) getView().findViewById(R.id.tvShippingCode);
		tvShippingCountry = (TextView) getView().findViewById(
				R.id.tvShippingCountry);
		tvRating = (TextView) getView().findViewById(R.id.tvRating);
		tvOwnership = (TextView) getView().findViewById(R.id.tvOwnership);
		tvIndustry = (TextView) getView().findViewById(R.id.tvIndustry);
		tvType = (TextView) getView().findViewById(R.id.tvType);
		tvWebsite = (TextView) getView().findViewById(R.id.tvWebSite);
		mSave = (Button) getView().findViewById(R.id.btSave1);
		mCancel = (Button) getView().findViewById(R.id.btCancel);
		mType = (Spinner) getView().findViewById(R.id.etType);
		mRating = (Spinner) getView().findViewById(R.id.etRating);
		mIndustry = (Spinner) getView().findViewById(R.id.etIndustry);
		mOwnerShip = (Spinner) getView().findViewById(R.id.etOwnership);
		billingToShipping = (TextView) getView().findViewById(
				R.id.tvBillingToShipping);

		abc = (ListView) getView().findViewById(R.id.contactListview);
		abc.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long arg3) {
				mHomeItemListener.onGetContacts(position, "accounts");
			}
		});
		billingToShipping.setOnClickListener(this);
		mSave.setOnClickListener(this);
		mCancel.setOnClickListener(this);

		etAccountNumber = (EditText) getView().findViewById(
				R.id.etAccountNumber);
		etAccountName = (EditText) getView().findViewById(R.id.etAccountName);
		etAnnuaLRevenue = (EditText) getView().findViewById(
				R.id.etAnnualRevenue);
		etBilingCity = (EditText) getView().findViewById(R.id.etBillingCity);
		etBilingcountry = (EditText) getView().findViewById(
				R.id.etBillingCountry);
		etBilingState = (EditText) getView().findViewById(R.id.etBillingState);
		etBilingStreet = (EditText) getView()
				.findViewById(R.id.etBillingStreet);
		etBilingZip = (EditText) getView().findViewById(R.id.etBillingCode);
		etEmployees = (EditText) getView().findViewById(R.id.etEmpoyees);
		etfax = (EditText) getView().findViewById(R.id.etFax);
		etParentAccount = (EditText) getView().findViewById(
				R.id.etParentAccount);
		etParentAccount.setOnClickListener(this);
		etPhone = (EditText) getView().findViewById(R.id.etPhone);
		etShippingcity = (EditText) getView().findViewById(R.id.etShippingCity);
		etShippingcode = (EditText) getView().findViewById(R.id.etShippingCode);
		etShippingCountry = (EditText) getView().findViewById(
				R.id.etShippingCountry);
		etshippingstate = (EditText) getView().findViewById(
				R.id.etShippingState);
		etShippingStreet = (EditText) getView().findViewById(
				R.id.etShippingStreet);
		etwebsite = (EditText) getView().findViewById(R.id.etWebSite);

		client = HomeActivity.mActivity.client;
		args = getArguments();
		if (args != null) {
			if (args.getInt("Position") == -1) {
				tbContactdisplaylayout.setVisibility(View.GONE);
				llayout.setVisibility(View.GONE);
				svAccount.setVisibility(View.VISIBLE);
				billingToShipping.setVisibility(View.VISIBLE);
			} else {
				billingToShipping.setVisibility(View.GONE);
				svAccount.setVisibility(View.GONE);
				llayout.setVisibility(View.VISIBLE);
				displayAccountDetails(args.getInt("Position"));
			}
		}

	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {

		case R.id.etParentAccount:
			AccountLookup lookUp = new AccountLookup();
			lookUp.accountLookupDetails(getActivity(), "Account");
			break;

		case R.id.btSave1:
			if (!flag) {
				createAccount();
			} else {
				updateAccount(parantAccountID);
			}
			break;

		case R.id.tvBillingToShipping:

			String billingCity = etBilingCity.getText().toString();
			if (billingCity != null) {
				etShippingcity.setText(billingCity);
			}
			String billingCountry = etBilingcountry.getText().toString();
			if (billingCountry != null) {
				etShippingCountry.setText(billingCountry);
			}

			String billingZip = etBilingZip.getText().toString();
			if (billingZip != null) {
				etShippingcode.setText(billingZip);
			}
			String billingState = etBilingState.getText().toString();
			if (billingState != null) {
				etshippingstate.setText(billingState);
			}
			String billingStreet = etBilingStreet.getText().toString();
			if (billingStreet != null) {
				etShippingStreet.setText(billingStreet);
			}
			break;

		case R.id.btCancel:
			// getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
			tbContactdisplaylayout.setVisibility(View.VISIBLE);
			billingToShipping.setVisibility(View.GONE);
			svAccount.setVisibility(View.GONE);
			llayout.setVisibility(View.VISIBLE);
			displayAccountDetails(args.getInt("Position"));

		default:
			break;
		}

	}

	public void editAcount() {

		etAccountName.setText(bean.getName());
		etfax.setText(bean.getFax());
		etAnnuaLRevenue.setText(bean.getAnnualRevenue());
		etEmployees.setText(bean.getNumberOfEmployees());
		etAccountNumber.setText(bean.getAccountNumber());
		etPhone.setText(bean.getPhno());
		etwebsite.setText(bean.getWebsite());
		etBilingCity.setText(bean.getBillingCity());
		etBilingcountry.setText(bean.getBillingCountry());
		etBilingState.setText(bean.getBillingState());
		etBilingStreet.setText(bean.getBillingStreet());
		etBilingZip.setText(bean.getBillingPostalCode());
		etShippingcity.setText(bean.getShippingCity());
		etShippingCountry.setText(bean.getShippingCountry());
		etshippingstate.setText(bean.getShippingState());
		etShippingcode.setText(bean.getShippingPostalCode());
		etShippingStreet.setText(bean.getShippingStreet());
		parantAccountID = bean.getId();
	}

	public void createAccount() {
		String objectType = "Account";
		HashMap<String, Object> fields = new HashMap<String, Object>();
		fields.put("Name", etAccountName.getText().toString());
		fields.put("AccountNumber", etAccountNumber.getText().toString());
		fields.put("AnnualRevenue", etAnnuaLRevenue.getText().toString());
		fields.put("Fax", etfax.getText().toString());
		fields.put("Phone", etPhone.getText().toString());
		fields.put("Website", etwebsite.getText().toString());
		fields.put("NumberOfEmployees", etEmployees.getText().toString());
		fields.put("Industry", mIndustry.getSelectedItem().toString());
		fields.put("Ownership", mOwnerShip.getSelectedItem().toString());
		fields.put("Type", mType.getSelectedItem().toString());
		fields.put("Rating", mRating.getSelectedItem().toString());
		fields.put("ParentId", parantAccountID);
		fields.put("BillingCity", etBilingCity.getText().toString());
		fields.put("BillingCountry", etBilingcountry.getText().toString());
		fields.put("BillingPostalCode", etBilingZip.getText().toString());
		fields.put("BillingState", etBilingState.getText().toString());
		fields.put("BillingStreet", etBilingStreet.getText().toString());
		fields.put("ShippingCity", etShippingcity.getText().toString());
		fields.put("ShippingCountry", etShippingCountry.getText().toString());
		fields.put("ShippingPostalCode", etShippingcode.getText().toString());
		fields.put("ShippingState", etshippingstate.getText().toString());
		fields.put("ShippingStreet", etShippingStreet.getText().toString());

		try {
			RestRequest restRequest = RestRequest.getRequestForCreate(
					Bean_Class.api_Version, objectType, fields);

			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {

						JSONObject json = new JSONObject(result.toString());
						if (json != null) {
							if (json.getString("success").equalsIgnoreCase(
									"true")) {

								etAccountNumber.setText("");
								etAccountName.setText("");
								etAnnuaLRevenue.setText("");
								etBilingCity.setText("");
								etBilingcountry.setText("");
								etBilingState.setText("");
								etBilingStreet.setText("");
								etBilingZip.setText("");
								etEmployees.setText("");
								etfax.setText("");
								etParentAccount.setText("");
								etPhone.setText("");
								etShippingcity.setText("");
								etShippingcode.setText("");
								etShippingCountry.setText("");
								etshippingstate.setText("");
								etShippingStreet.setText("");
								etwebsite.setText("");
								mHomeItemListener.onCategoryClicked(-2);
							}

						}

					} catch (Exception e) {
						Log.i("TPT", "Exception is   :" + e.getMessage());
					}
				}

				// @Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(
							EventType.RenditionComplete);
				}
			});
		} catch (Exception e) {
			Log.i("NCS", "Exception is   :" + e.getMessage());

		}

	}

	public void updateAccount(String id) {

		String objectType = "Account";
		HashMap<String, Object> fields = new HashMap<String, Object>();
		fields.put("Name", etAccountName.getText().toString());
		fields.put("AccountNumber", etAccountNumber.getText().toString());
		fields.put("AnnualRevenue", etAnnuaLRevenue.getText().toString());
		fields.put("Fax", etfax.getText().toString());
		fields.put("Phone", etPhone.getText().toString());
		fields.put("Website", etwebsite.getText().toString());
		fields.put("NumberOfEmployees", etEmployees.getText().toString());
		fields.put("Industry", mIndustry.getSelectedItem().toString());
		fields.put("Ownership", mOwnerShip.getSelectedItem().toString());
		fields.put("Type", mType.getSelectedItem().toString());
		fields.put("Rating", mRating.getSelectedItem().toString());
		fields.put("ParentId", Session.sParentId);
		fields.put("BillingCity", etBilingCity.getText().toString());
		fields.put("BillingCountry", etBilingcountry.getText().toString());
		fields.put("BillingPostalCode", etBilingZip.getText().toString());
		fields.put("BillingState", etBilingState.getText().toString());
		fields.put("BillingStreet", etBilingStreet.getText().toString());
		fields.put("ShippingCity", etShippingcity.getText().toString());
		fields.put("ShippingCountry", etShippingCountry.getText().toString());
		fields.put("ShippingPostalCode", etShippingcode.getText().toString());
		fields.put("ShippingState", etshippingstate.getText().toString());
		fields.put("ShippingStreet", etShippingStreet.getText().toString());

		try {
			RestRequest restRequest = RestRequest.getRequestForUpdate(
					Bean_Class.api_Version, objectType, id, fields);

			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {
						tbContactdisplaylayout.setVisibility(View.VISIBLE);
						billingToShipping.setVisibility(View.GONE);
						svAccount.setVisibility(View.GONE);
						llayout.setVisibility(View.VISIBLE);
						displayAccountDetails(args.getInt("Position"));

					} catch (Exception e) {
						Log.i("TPT", "Exception is   :" + e.getMessage());
					}
				}

				// @Override
				public void onError(Exception exception) {
					Toast.makeText(
							getActivity(),
							AccountsdetailsFragment.this.getString(
									SalesforceSDKManager.getInstance()
									.getSalesforceR()
									.stringGenericError(),
									exception.toString()), Toast.LENGTH_LONG)
									.show();
					EventsObservable.get().notifyEvent(
							EventType.RenditionComplete);
				}
			});
		} catch (Exception e) {
			Log.i("NCS", "Exception is   :" + e.getMessage());

		}

	}

	public void displayAccountDetails(int position) {

		tvAccountOwner.setText(Session.sFirstName + " " + Session.sLastName);
		bean = AccountsFragment.list.get(position);
		Session.sAccountName = bean.getName();
		tvAccountName.setText(bean.getName());
		tvfax.setText(bean.getFax());
		tvAnnuaLRevenue.setText(bean.getAnnualRevenue());
		tvEmployees.setText(bean.getNumberOfEmployees());
		tvAccountNumber.setText(bean.getAccountNumber());
		tvPhone.setText(bean.getPhno());
		tvWebsite.setText(bean.getWebsite());
		tvBilingCity.setText(bean.getBillingCity());
		tvBilingcountry.setText(bean.getBillingCountry());
		tvBilingState.setText(bean.getBillingState());
		tvBilingStreet.setText(bean.getBillingStreet());
		tvBilingZip.setText(bean.getBillingPostalCode());
		tvShippingcity.setText(bean.getShippingCity());
		tvShippingCountry.setText(bean.getShippingCountry());
		tvshippingstate.setText(bean.getShippingState());
		tvShippingcode.setText(bean.getShippingPostalCode());
		tvShippingStreet.setText(bean.getShippingStreet());

		tvRating.setText(bean.getRating());
		tvOwnership.setText(bean.getOwnership());
		tvIndustry.setText(bean.getIndustry());
		tvType.setText(bean.getType());

		getContacts(bean.getId());
		progressDialog = biznussoft.fieldservice360.utils.ProgressDialog
				.getInstance().createProgressDialog(getActivity());
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.show();

	}

	public void getContacts(String id) {

		try {

			String accounts = "Select id,LastName,FirstName,AccountId,Title,Phone,MobilePhone,Email,MailingStreet,MailingCity,MailingState,MailingCountry,MailingPostalCode,OtherStreet,OtherCity,OtherState,OtherPostalCode,OtherCountry from Contact where AccountId ="
					+ "'" + id + "'";
			RestRequest restRequest = RestRequest.getRequestForQuery(
					getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {
						JSONObject jsonObject1 = new JSONObject(result
								.asString());
						JSONArray jsonArray = jsonObject1
								.getJSONArray("records");
						contactList = new ArrayList<ContactsModel>();
						Gson _gson = new Gson();
						for (int i = 0; i < jsonArray.length(); i++) {
							if (!jsonArray.isNull(i)) {
								ContactsModel bean = _gson.fromJson(
										jsonArray.getString(i),
										ContactsModel.class);
								contactList.add(bean);
							}
						}

						if (contactList.size() > 0) {
							ContactsAdapter adapter = new ContactsAdapter(
									getActivity(), contactList);
							abc.setAdapter(adapter);

						}

						progressDialog.dismiss();

					} catch (Exception e) {
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					Toast.makeText(
							getActivity(),
							AccountsdetailsFragment.this.getString(
									SalesforceSDKManager.getInstance()
									.getSalesforceR()
									.stringGenericError(),
									exception.toString()), Toast.LENGTH_LONG)
									.show();
					EventsObservable.get().notifyEvent(
							EventType.RenditionComplete);

				}
			});

		} catch (Exception e) {
			Log.i("NCS", "Exception  2 is  :" + e.getMessage());
		}

	}

}
